﻿/**************************************************************
 *
 * 唯一标识：47f83776-020d-440d-9339-1ebba8ec84ab
 * 命名空间：Sgr.UPMS.Application.Commands.Organizations
 * 创建时间：2023/8/24 17:08:41
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Organizations;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Organizations
{
    public class AssociatedParentOrgCommandHandle : IRequestHandler<AssociatedParentOrgCommand, CommandResult<bool>>
    {
        private readonly IOrganizationManage _organizationManage;

        public AssociatedParentOrgCommandHandle(IOrganizationManage organizationManage)
        {
            _organizationManage = organizationManage;
        }

        /// <summary>
        /// 处理组织机构关联上级命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(AssociatedParentOrgCommand request, CancellationToken cancellationToken)
        {
            // 如果是自己关联自己，返回错误
            if (request.ParentId.HasValue && request.Id == request.ParentId.Value)
                return CommandResult.Invalid<bool>("组织机构不能关联自己作为上级");

            var moveResult = await _organizationManage.MoveNodeAsync(request.Id, request.ParentId ?? 0, 5, cancellationToken);
            if (!moveResult.IsComply)
                return CommandResult.Invalid<bool>($"关联上级组织操作失败, {moveResult.Message}");

            // 返回成功结果
            return CommandResult.Success(true, "关联上级组织成功");
        }
    }
}